<?php
/**
 * @copyright        2016 opencart.cn - All Rights Reserved
 * @link             http://www.guangdawangluo.com
 * @author           TL <mengwb@opencart.cn>
 * @created          2016-12-13 17:04:00
 * @modified         2016-12-13 17:04:00
 */

class ModelAccountWeixinLogin extends Model
{
    public function getCustomerInfoByOpenid($openid)
    {
        $query = $this->db->query("SELECT c.*, a.uid, a.unionid FROM " . DB_PREFIX . "customer c
                                   LEFT JOIN " . DB_PREFIX . "customer_authentication a ON c.customer_id = a.customer_id
                                   WHERE uid = '" . $this->db->escape($openid) . "'");
        return $query->row;
    }

    public function getCustomerInfoByUid($unionid)
    {
        $query = $this->db->query("SELECT c.*, a.uid AS open_id, a.unionid AS uid FROM " . DB_PREFIX . "customer c
                                   LEFT JOIN " . DB_PREFIX . "customer_authentication a ON c.customer_id = a.customer_id
                                   WHERE unionid = '" . $this->db->escape($unionid) . "'");
        return $query->row;
    }

    public function bindCustomer($customer_id, $userinfo)
    {
        $query = $this->db->query("SELECT customer_id FROM " . DB_PREFIX . "customer_authentication WHERE customer_id = '" . (int)$customer_id . "'");
        if ($query->num_rows) {
          $this->db->query("UPDATE " . DB_PREFIX . "customer_authentication SET customer_id = " . (int)$customer_id . " WHERE uid = '" . $this->db->escape($userinfo['openid']) . "'");
        } else {
          $this->db->query("DELETE FROM " . DB_PREFIX . "customer_authentication WHERE uid = '" . $this->db->escape($userinfo['openid']) . "'");
        }
        $sql = "INSERT INTO " . DB_PREFIX . "customer_authentication (`customer_id`, `uid`, `unionid`, `provider`, `access_token`, `date_added`, `date_modified`) VALUES ('{$customer_id}', '{$userinfo['openid']}', '{$userinfo['unionid']}', 'weixin_gz', '{$userinfo['access_token']}', NOW(), NOW())";
        $this->db->query($sql);
        $this->updateCustomerHeadimgurl($this->session->data['userinfo']['openid'], $this->session->data['userinfo']['headimgurl']);
        if (isset($this->session->data['userinfo']['unionid'])) {
            $this->updateCustomerUnionid($this->session->data['userinfo']['openid'], $this->session->data['userinfo']['unionid']);
        }
    }

    public function isOpenidExist($openid)
    {
        $query = $this->db->query("SELECT uid FROM " . DB_PREFIX . "customer c
                                   LEFT JOIN " . DB_PREFIX . "customer_authentication a ON c.customer_id = a.customer_id
                                   WHERE uid = '" . $this->db->escape($openid) . "'");
        if ($query->num_rows) {
            return $query->row['uid'];
        } else {
            return 0;
        }
    }

    public function isUnionidExist($unionid)
    {
        $query = $this->db->query("SELECT unionid FROM " . DB_PREFIX . "customer c
                                   LEFT JOIN " . DB_PREFIX . "customer_authentication a ON c.customer_id = a.customer_id
                                   WHERE unionid = '" . $this->db->escape($unionid) . "'");
        if ($query->num_rows) {
            return $query->row['unionid'];
        } else {
            return 0;
        }
    }

    public function addWeixinCustomer($userinfo)
    {
        $customer_group_id = $this->config->get('config_customer_group_id');

        $this->load->model('account/customer_group');
        $this->load->model('account/customer');

        $data = array(
            'customer_group_id' => (int)$customer_group_id,
            'firstname' => $this->removeEmoji($userinfo['nickname']),
            'email' => '', //md5($openid),
            'telephone' => '',
            'fax' => '',
            'password' => uniqid(rand(), true),
            'company' => ''
        );
        $customerId = $this->model_account_customer->addCustomer($data);

        $this->bindCustomer($customerId, $userinfo);
        $this->updateCustomerHeadimgurl($userinfo['openid'], $userinfo['headimgurl']);

        return $customerId;
    }

    public function updateCustomerHeadimgurl($openid, $headimgurl)
    {
        $query = $this->db->query("SELECT cp.avatar, cp.id, c.customer_id FROM " . DB_PREFIX . "customer c
                                   LEFT JOIN " . DB_PREFIX . "customer_profile cp ON c.customer_id = cp.customer_id
                                   LEFT JOIN " . DB_PREFIX . "customer_authentication a ON c.customer_id = a.customer_id
                                   WHERE uid = '" . $this->db->escape($openid) . "'");

        if($query->num_rows && !$query->row['avatar']){
            $this->load->model('tool/image');
            $result = $this->model_tool_image->getImage($headimgurl, DIR_IMAGE . 'avatar/', $query->row['customer_id'] . 'avatar.jpg');
            if (!$result['error']) {
                $avatar = 'avatar/'. $query->row['customer_id'] . 'avatar.jpg';
                if ($query->row['id']) {
                    $this->db->query("UPDATE " . DB_PREFIX . "customer_profile SET avatar = '" . $avatar . "' WHERE id = '" . $query->row['id'] . "'");
                } else {
                    $this->db->query("INSERT " . DB_PREFIX . "customer_profile SET avatar = '" . $avatar . "', customer_id = '" . $query->row['customer_id'] . "', created_at = NOW(), updated_at = NOW()");
                }
            }
        }
    }

    public function updateCustomerUnionid($openid, $unionid)
    {
        $this->db->query("UPDATE " . DB_PREFIX . "customer_authentication SET unionid = '" . $unionid . "' WHERE uid = '" . $openid . "'");
    }

    public function updateCustomerOpenid($unionid, $openid)
    {
        $this->db->query("UPDATE " . DB_PREFIX . "customer_authentication SET uid = '" . $openid . "' WHERE unionid = '" . $unionid . "'");
    }

    private function removeEmoji($text) {
        $clean_text = "";
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $text);
        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);
        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);
        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);
        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);
        return $clean_text;
    }
}
